package com.dance.java8.day01;

import com.dance.java8.entity.Person;
import org.junit.Test;

import java.util.Optional;

public class TestOptional {

    /**
     * 常用方法
     * Optional.of(T t) - 创建一个Optional的实例
     * Optional.empty() - 创建一个空的Optional实例
     * Optional.ofNullable(T t) - 若t不为null 创建Optional实例,否则创建空实例
     * isPresent() - 判断是否包含值
     * orElse(T t) - 如果调用对象包含值,返回该值,否则返回t
     * orElseGet(Supplier s) - 如果调用对象包含值,返回该值,否则返回s获取的值
     * map(Function f) - 如果有值对其处理,并返回处理后的Optional,否则返回Optional.empty
     * flatMap(Function mapper) - 与Map类似,要求返回值必须是Optional
     */
    @Test
    public void test1(){
        // 创建一个人员
        Optional<Person> person = Optional.of(new Person());
        // 获取其中的值
        Person person1 = person.get();
        System.out.println("get method : " + person1);
    }

    @Test
    public void test2(){
        Optional<Object> empty = Optional.empty();
        System.out.println(empty);
    }

    @Test
    public void test3(){
        Optional<Object> empty = Optional.ofNullable(null);
        System.out.println(empty);
        Optional<Object> empty1 = Optional.ofNullable(new Person());
        System.out.println(empty1);
    }

    @Test
    public void test4(){
        Optional<Object> empty = Optional.ofNullable(null);
        System.out.println(empty.isPresent());
        Optional<Object> empty1 = Optional.ofNullable(new Person());
        System.out.println(empty1.isPresent());
    }

    @Test
    public void test5(){
        Optional<Object> empty = Optional.ofNullable(null);
        System.out.println(empty.orElse("this is null"));
        Optional<Object> empty1 = Optional.ofNullable(new Person());
        System.out.println(empty1.orElse("this is null"));
    }

    @Test
    public void test6(){
        Optional<Object> empty = Optional.ofNullable(null);
        System.out.println(empty.orElseGet(Person::new));
    }

    @Test
    public void test7(){
        Optional<Person> empty = Optional.of(new Person("lisa", 18));
        Optional<String> s = empty.map(Person::getName);
        System.out.println(s.get());
    }

    @Test
    public void test8(){
        Optional<Person> empty = Optional.of(new Person("lisa", 18));
        Optional<String> s = empty.flatMap(e -> Optional.of(e.getName()));
        System.out.println(s.get());
    }

}
